﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Net;
using System.IO;
using System.IO.Compression;
using System.Text.RegularExpressions;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml;
using System.Threading;


namespace MillionArthurTool
{
    public partial class Form1 : Form
    {
        private Log actionlog;
        private static readonly string DefaultUserAgent = "Million/100 (c1lgt; c1lgt; 4.1.2) samsung/c1lgt/c1lgt:4.1.2/JZO54K/E210LKLJLL7:user/release-keys GooglePlay";
        private string key0;
        private string key11;
        private string key12;
        private string baseKey;
        private string szCookie;
        private string cardFull;
        private string cardMr;
        private string card3;
        private string lr3;
        private string card6;
        private string lr6;
        private string cardSUB;
        private string lrSUB;
        private string cardMaid;
        private string lrMaid;
        private string cardwolf;
        private string lrwolf;
        private string szFloor = "1";
        private string szActionLog = "";
        private string AreaName = "";
        private string szCharName = "";
        private string szSkill = "dummy";
        private string bname;
        private string labelgrk;
        private string labelgzg;
        private string labelzzg;
        private string labelzrg;
        private string labelzrk;
        private string labelxzg;
        private string labelxrg;
        private string labelxrk;
        private string szcookie;
        private int BC = 0;
        private int MaxBc = 0;
        private int AP = 0;
        private int MaxAP = 0;
        private int iNowUserid = 0;
        private int iPartyid = 0;
        private int iSellPrice = 600;
        private int iAreaID = 0;
        private int LoginType = 1;
        private int ilowap = 1;
        private int iCardNum = 0;
        private int iGuildID = 0;
        private int master_boss_id;
        private int iMasterBossID = 0;
        private int serial_id;
        private int lv;
        private int hp;
        private int hp_max;
        private int iJobID = 0;
        private int iSubBossID = 0;
        private int iContribution = 0;
        private int iContribution2 = 0;
        private bool bWinner = false;
        private bool bAutoChange = false;
        private bool bliqu = true;
        private bool bBonus = false;
        private bool bSub = false;

        private bool bActNoLimit = false;
        private bool bNoLimitedBC = false;
        private bool bxiap = false;

        private bool bThreadMain = false;
        private bool bThreadRank = false;
        private bool bThreadAttack = false;
        private bool bThreadExplore = false;
        private bool bThreadRigist = false;

        private bool bAttack = false;

        private XmlDocument areaxml;
        private XmlNodeList cardlist;

        private Thread MainThread;
        private Thread RankThread;
        private Thread AttackThread;
        private Thread ExploreThread;
        private Thread RigistThread;


        private bool bLogin = false;

        public event EventHandler<EventArgs> AttackEvent;
        public event EventHandler<EventArgs> ExploreEvent;
        public event EventHandler<EventArgs> LoginEvent;
        public event EventHandler<EventArgs> MapsEvent;
        public event EventHandler<EventArgs> RewardsEvent;

        List<playerrank> ranklist = new List<playerrank>();
        void AttackMethod(object sender, EventArgs e)
        {
            int ilowbc = 2;
            try
            {
                ilowbc = int.Parse(textBox5.Text);
            }
            catch (System.Exception ex)
            {

            }
            if (BC >= ilowbc) getFairyIfo();
            else if (radioButton4.Checked)
            {
                useitem(2);
                if (BC > ilowbc) getFairyIfo();
            }
            else if (radioButton5.Checked)
            {
                useitem(111);
                if (BC > ilowbc) getFairyIfo();
            }
            else
            {
                getapbc();
            }
        }
        bool bExplore = true;
        void ExploreMethod(object sender, EventArgs e)
        {
            button7.Enabled = false;
            int ire = getapbc();
            while (ire == 3) getapbc();
            if (AP >= ilowap) while (AP >= ilowap && 3 != explore()) ;
            else if (radioButton7.Checked)
            {
                useitem(1); while (AP >= ilowap && 3 != explore()) ;
            }
            else if (radioButton6.Checked)
            {
                useitem(101); while (AP >= ilowap && 3 != explore()) ;
            }


            button7.Enabled = true;
        }

        void MapsMethod(object sender, EventArgs e)
        {
            GetAreaIfo();
        }

        void LoginMethod(object sender, EventArgs e)
        {
            EnableLoint(!bLogin);
        }
        void RewardsMethod(object sender, EventArgs e)
        {
            try
            {
                iSellPrice = int.Parse(textBox4.Text);
            }
            catch (System.Exception ex)
            {

            }
            try
            {
                while (-1 != getRewardsAll());
            }
            catch (System.Exception ex)
            {
                szActionLog += "[" + DateTime.Now.ToString() + "]" + ex.Message + "\r\n";
                actionlog.WriteInfo(ex.Message + "\r\n");
            }
            button5.Enabled = true;
        }
        public Form1()
        {
            InitializeComponent();
            AttackEvent += new EventHandler<EventArgs>(AttackMethod);
            ExploreEvent += new EventHandler<EventArgs>(ExploreMethod);
            LoginEvent += new EventHandler<EventArgs>(LoginMethod);
            MapsEvent += new EventHandler<EventArgs>(MapsMethod);
            RewardsEvent += new EventHandler<EventArgs>(RewardsMethod);
            actionlog = Log.instance;
            GetApple();
            timer1.Interval = 1000;
            timer1.Start();
            key0 = baseKey;
        }



        int iArthaCount = 0;
        int[] arthalist = new int[10];
        private int GetAP()
        {
            if (!bDM)
            {
                return -1;
            }
            while (iArthaCount == 0 || iArthaNum == -1 || iArthaNum == iArthaCount)
            {
                SearchArtha();
            }
            //ChangeCard(CardChose.ibase3cardnum);
            int ire = 0;
            if (BC >= 5) AtactArtha(arthalist[iArthaNum]);
            return ire;
        }
        private int SearchArtha()
        {
            int iRe = -1;
            IDictionary<string, string> parameters = new Dictionary<string, string>()
            {
                {"",""}
            };
            string s0 = "0";
            parameters.Clear();
            parameters.Add("name", Encrypt("无名亚", key12));
            string ulr = "http://game1-CBT.ma.sdo.com:10001/connect/app/menu/player_search?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = "game1-CBT.ma.sdo.com";
            cookies.Add(c);
            XmlDocument xml = null;

            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue;
                }
            }

            if (xml.InnerText != "")
            {
                try
                {
                    szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                    if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                    {
                        return iRe;
                    }
                    XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("player_search").SelectSingleNode("user_list");
                    iArthaCount = 0;
                    for (int i = 0; i < 9; i++)
                    {
                        if (int.Parse(node0.ChildNodes[i + 1].SelectSingleNode("town_level").InnerText) < 5)
                        {
                            arthalist[iArthaCount] = int.Parse(node0.ChildNodes[i + 1].SelectSingleNode("id").InnerText);
                            iArthaCount++;
                        }
                    }
                    iArthaNum = 0;

                    iRe = 0;
                }
                catch (System.Exception ex)
                {
                }
            }
            return iRe;
        }

        DateTime dtold = DateTime.Now;
        bool bDM = false;
        int iArthaNum = 0;
        private int AtactArtha(int iArtha)
        {
            int iRe = -1;
            DateTime dt = DateTime.Now;
            TimeSpan ts = dt - dtold;
            if (ts.TotalSeconds < 16 || !bDM)
            {
                return iRe;
            }
            iArthaNum++;
            IDictionary<string, string> parameters = new Dictionary<string, string>()
            {
                {"",""}
            };
            string s0 = "0";
            parameters.Clear();
            parameters.Add("lake_id", Encrypt(s0, key12));
            parameters.Add("parts_id", Encrypt(s0, key12));
            parameters.Add("user_id", Encrypt(iArtha.ToString(), key12));
            string ulr = "http://game1-CBT.ma.sdo.com:10001/connect/app/battle/battle?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = "game1-CBT.ma.sdo.com";
            cookies.Add(c);
            XmlDocument xml = null;

            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue;
                }
            }

            if (xml.InnerText != "")
            {
                string szlogtemp = "点名：";
                try
                {
                    szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                    if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                    {
                        System.Diagnostics.Trace.WriteLine("error code :" + xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText
                            + " message: " + xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("message").InnerText + "\r\n");
                        szlogtemp += xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("message").InnerText + "\r\n";
                        szActionLog += "[" + DateTime.Now.ToString() + "]" + szlogtemp; actionlog.WriteInfo(szlogtemp);
                        return int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText);
                    }
                    XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("your_data"); szCharName = node0.SelectSingleNode("name").InnerText;
                    XmlNode nodeBC = node0.SelectSingleNode("bc");
                    int oldAp = AP;
                    int oldBC = BC;
                    BC = int.Parse(nodeBC.SelectSingleNode("current").InnerText);
                    MaxBc = int.Parse(nodeBC.SelectSingleNode("max").InnerText);
                    XmlNode nodeAP = node0.SelectSingleNode("ap");
                    AP = int.Parse(nodeAP.SelectSingleNode("current").InnerText);
                    MaxAP = int.Parse(nodeAP.SelectSingleNode("max").InnerText);

                    szlogtemp += "AP:" + oldAp.ToString() + "-" + AP.ToString() + " BC:" + oldBC.ToString() + "-" + BC.ToString() + "\r\n";
                    szActionLog += "[" + DateTime.Now.ToString() + "]" + szlogtemp; actionlog.WriteInfo(szlogtemp);
                    iRe = 0;

                    dtold = dt;
                }
                catch (System.Exception ex)
                {
                    szlogtemp += ex.Message + "\r\n";
                    szActionLog += "[" + DateTime.Now.ToString() + "]" + szlogtemp; actionlog.WriteInfo(szlogtemp);
                }
            }
            return iRe;
        }




        int geturerrank(int iUser)
        {
            int iRank = 0;
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = "game1-CBT.ma.sdo.com";
            cookies.Add(c);
            string ulr = "http://game1-CBT.ma.sdo.com:10001/connect/app/ranking/ranking_next?cyt=1";
            IDictionary<string, string> parameters = new Dictionary<string, string>()
                {
                    {"",""}
                };
            parameters.Clear();
            if (iNowUserid == 0)
            {
                iNowUserid = getuserid();
            }
            // area_id=PWB4JL4LM1oYO7VbS8W7YQ%3D%3D%0A&auto_build=aieM12Y9tyl65ZBPd6GyUg%3D%3D%0A&floor_id=dcGs4R%2B%2FFzSWUgTwaO5wag%3D%3D%0A
            parameters.Add("from", Encrypt(iUser.ToString(), key12));
            parameters.Add("ranktype_id", Encrypt("4", key12));

            XmlDocument xml = null;
            while (true)
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                }
            if (xml != null)
            {
                XmlNodeList xmllist = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("ranking").SelectSingleNode("user_list").SelectNodes("user");
                iRank = int.Parse(xmllist[0].SelectSingleNode("rank").InnerText) - 1;
            }
            return iRank;
        }
        private int getXSparty()
        {
            int ipart = 0;
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = "game1-CBT.ma.sdo.com";
            cookies.Add(c);
            string ulr = "http://game1-CBT.ma.sdo.com:10001/connect/app/guild/guild_member_list?cyt=1";
            IDictionary<string, string> parameters = new Dictionary<string, string>()
                {
                    {"",""}
                };
            parameters.Clear();
            if (iNowUserid == 0)
            {
                iNowUserid = getuserid();
            }
            // area_id=PWB4JL4LM1oYO7VbS8W7YQ%3D%3D%0A&auto_build=aieM12Y9tyl65ZBPd6GyUg%3D%3D%0A&floor_id=dcGs4R%2B%2FFzSWUgTwaO5wag%3D%3D%0A
            parameters.Add("guild_member_type", Encrypt("1", key12));

            XmlDocument xml = null;
            while (true)
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                }
            if (xml != null)
            {
                XmlNodeList xmllist = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("guild_member_list").SelectSingleNode("guild_party_list").SelectNodes("ex_party");
                int imaxPoint = 0; string szxsname = ""; string szxsleadername = "";
                foreach (XmlNode xmlparty in xmllist)
                {
                    int ipoint = int.Parse(xmlparty.SelectSingleNode("hunting_point").InnerText);
                    if (ipoint > imaxPoint)
                    {
                        imaxPoint = ipoint;
                        szxsname = xmlparty.SelectSingleNode("party").SelectSingleNode("name").InnerText;
                        szxsleadername = xmlparty.SelectSingleNode("party").SelectSingleNode("leader").SelectSingleNode("name").InnerText;
                        ipart = int.Parse(xmlparty.SelectSingleNode("party").SelectSingleNode("id").InnerText);

                    }

                }

                string szXrank = "对面团：" + szxsname + "，团长：" + szxsleadername + "贡献：" + imaxPoint + "/" + labelxzg + " | " + labelxrg + " | " + labelxrk + "\r\n\r\n";
                szActionLog += szXrank;
                partyrank(ipart);
            }
            return ipart;
        }
        private void partyrank(int iid)
        {
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = "game1-CBT.ma.sdo.com";
            cookies.Add(c);
            string ulr = "http://game1-CBT.ma.sdo.com:10001/connect/app/party/party_only_member_list?cyt=1";
            IDictionary<string, string> parameters = new Dictionary<string, string>()
                {
                    {"",""}
                };
            parameters.Clear();
            // area_id=PWB4JL4LM1oYO7VbS8W7YQ%3D%3D%0A&auto_build=aieM12Y9tyl65ZBPd6GyUg%3D%3D%0A&floor_id=dcGs4R%2B%2FFzSWUgTwaO5wag%3D%3D%0A
            parameters.Add("pid", Encrypt(iid.ToString(), key12));

            XmlDocument xml = null;
            while (true)
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                }
            if (xml != null)
            {
                ranklist.Clear();
                XmlNodeList xmllist = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("party_member_list").SelectNodes("member");
                int itotalrank = 0;
                foreach (XmlNode nodes in xmllist)
                {
                    playerrank rank1 = new playerrank();
                    int id = int.Parse(nodes.SelectSingleNode("id").InnerText);
                    rank1.name = nodes.SelectSingleNode("name").InnerText;
                    itotalrank += rank1.point = int.Parse(nodes.SelectSingleNode("guild_hunting_point").InnerText);
                    rank1.ilv = int.Parse(nodes.SelectSingleNode("town_level").InnerText);
                    rank1.logintime = nodes.SelectSingleNode("last_login").InnerText;
                    rank1.irank = geturerrank(id);
                    ranklist.Add(rank1);
                }
                ranklist.Sort();
                foreach (playerrank rank in ranklist)
                {
                    szActionLog += rank.ToString() + "\r\n";
                }
            }
        }
        private void partyrank()
        {
            button4.Enabled = false;
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = "game1-CBT.ma.sdo.com";
            cookies.Add(c);
            string ulr = "http://game1-CBT.ma.sdo.com:10001/connect/app/party/party_only_member_list?cyt=1";
            IDictionary<string, string> parameters = new Dictionary<string, string>()
                {
                    {"",""}
                };
            parameters.Clear();
            // area_id=PWB4JL4LM1oYO7VbS8W7YQ%3D%3D%0A&auto_build=aieM12Y9tyl65ZBPd6GyUg%3D%3D%0A&floor_id=dcGs4R%2B%2FFzSWUgTwaO5wag%3D%3D%0A
            parameters.Add("pid", Encrypt(iPartyid.ToString(), key12));

            XmlDocument xml = null;
            while(true)
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                }
            if (xml != null)
            {
                FileStream sw = new FileStream("基佬排名.txt", FileMode.OpenOrCreate);
                ranklist.Clear();
                XmlNodeList xmllist = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("party_member_list").SelectNodes("member");
                int itotalrank = 0;
                foreach (XmlNode nodes in xmllist)
                {
                    playerrank rank1 = new playerrank();
                    int id = int.Parse(nodes.SelectSingleNode("id").InnerText);
                    rank1.name = nodes.SelectSingleNode("name").InnerText;
                    itotalrank += rank1.point = int.Parse(nodes.SelectSingleNode("guild_hunting_point").InnerText);
                    rank1.ilv = int.Parse(nodes.SelectSingleNode("town_level").InnerText);
                    rank1.logintime = nodes.SelectSingleNode("last_login").InnerText;
                    rank1.irank = geturerrank(id);
                    ranklist.Add(rank1);
                }
                getRankINFO();
                string szGrank = "团贡 ：" + itotalrank.ToString() + "/" + labelzzg + "，日贡：" + labelzrg + "，团排：" + labelzrk + "\r\n";
                ranklist.Sort();
                foreach (playerrank rank in ranklist)
                {
                    byte[] ay = UTF8Encoding.UTF8.GetBytes(rank.ToString());
                    sw.Write(ay, 0, ay.Length);
                    sw.Flush();
                    szActionLog += rank.ToString() + "\r\n";
                }
                szActionLog += szGrank;
                sw.Close();

                getXSparty();
            }
            button4.Enabled = true;
        }
        private bool Login()
        {
            bool bReturn = false;
            string user = textBox1.Text;
            if (LoginType == 0)
            {
                selectKey(user);
                string str = textBox2.Text;
                CookieCollection cookies = new CookieCollection();
                Cookie c = new Cookie("S", "");
                c.Domain = "game1-CBT.ma.sdo.com";
                //cookies.Add(c);
                string ulr = "http://game1-CBT.ma.sdo.com:10001/connect/app/login?cyt=1";
                IDictionary<string, string> parameters = new Dictionary<string, string>()
                {
                    {"",""}
                };
                parameters.Clear();
                parameters.Add("login_id", Encrypt(user, key0));
                parameters.Add("password", Encrypt(str, key0));

                XmlDocument xml = null;
                while (true)
                    try
                    {
                        xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                        break;
                    }
                    catch (System.Exception ex)
                    {
                    }
                if (xml != null)
                {

                    if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                    {
                        string szlogtemp = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("message").InnerText + "\r\n";
                        szActionLog += "[" + DateTime.Now.ToString() + "]" + szlogtemp; actionlog.WriteInfo(szlogtemp);
                    }
                    else
                    {
                        szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;

                        XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("your_data"); szCharName = node0.SelectSingleNode("name").InnerText;
                        XmlNode nodeBC = node0.SelectSingleNode("bc");
                        BC = int.Parse(nodeBC.SelectSingleNode("current").InnerText);
                        MaxBc = int.Parse(nodeBC.SelectSingleNode("max").InnerText);
                        XmlNode nodeAP = node0.SelectSingleNode("ap");
                        AP = int.Parse(nodeAP.SelectSingleNode("current").InnerText);
                        MaxAP = int.Parse(nodeAP.SelectSingleNode("max").InnerText);
                        cardlist = node0.SelectSingleNode("owner_card_list").SelectNodes("user_card");

                        //iPartyid = int.Parse(node0.SelectSingleNode("party_id").InnerText);
                        try
                        {
                            XmlNode node1 = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("login").SelectSingleNode("user_id");
                            iNowUserid = int.Parse(node1.InnerText);
                        }
                        catch (System.Exception ex)
                        {
                            iNowUserid = getuserid();
                        }
                        szActionLog += "登录成功\r\ncookie:" + szCookie + "|user:" + iNowUserid.ToString() + "|name:" + szCharName +"\r\n";
                        bReturn = true;
                    }
                }
            }
            else
            {
                selectKey(user);
                szCookie  = textBox3.Text;
                iNowUserid = getuserid();
                if (iNowUserid != 0)
                {
                    bReturn = true;
                }
                else
                {
                    szActionLog += "user/cookie不匹配或者cookie失效\r\n";
                }
            }
            return bReturn;
        }
        private void threadMain()
        {
            szActionLog += "开始登陆\r\n";
            if (!Login())
            {
                LoginEvent.BeginInvoke(null, EventArgs.Empty, null, null);
                return;
            }
            bThreadMain = true;
            bLogin = true;
//             RankThread = new Thread(threadRank);
//             RankThread.Start();
            //             szActionLog += "开启rank监视\r\n";
            button3.Enabled = true;
            button4.Enabled = true;
            button5.Enabled = true;
            button7.Enabled = true;
            button9.Enabled = true;
            button10.Enabled = true;
            fairylist.Clear();
            button8.Enabled = true;
            GetAreaIfo();
            button6.Enabled = true;
            //UpdateJob();
            while (bThreadMain)
            {
                int ilowbc = 2;
                try
                {
                    ilowbc = int.Parse(textBox5.Text);
                }
                catch (System.Exception ex)
                {

                }
                while (!bThreadAttack) Thread.Sleep(1000);
                if (BC < ilowbc) getapbc();
                //if (serial_id == 0) getGuidIFO();
                Thread.Sleep(1000);
            }
        }
        private void threadRank()
        {
            while (bThreadRank)
            {
                getRankINFO();
                Thread.Sleep(30000);
            }
        }
        private void threadAttack()
        {
            while (bThreadAttack)
            {
                AttackEvent.BeginInvoke(null, EventArgs.Empty, null, null);
                Thread.Sleep(12000);
            }
        }
        private void threadExplore()
        {
            int ire = getapbc();
            int ilowAP = 0;
            while (bThreadExplore)
            {
                try
                {
                    ilowAP = int.Parse(textBox6.Text);
                }
                catch (System.Exception ex)
                {

                }
                if (bDM && BC > 5)
                {
                    GetAP();
                }
                if ((bDM && BC == MaxBc))
                {
                    Thread.Sleep(1000);
                    ire = getapbc();
                }
                else if ( (!bExplore^!checkBox4.Checked) && AP!=MaxAP)
                {
                    Thread.Sleep(1000);
                    ire = getapbc();
                }
                else if (AP >= ilowap && AP >= ilowAP)
                {
                    ire = explore();
                }
                else if (radioButton7.Checked)
                {
                    useitem(1);
                    if (AP >= ilowap && AP >= ilowAP) ire = explore();
                }
                else if (radioButton6.Checked)
                {
                    useitem(101);
                    if (AP >= ilowap && AP >= ilowAP) ire = explore();
                }
                else if (bDM && BC > 5)
                {
                    GetAP();
                }
                else
                {
                    Thread.Sleep(60000);
                    ire = getapbc();
                }
            }
        }
        private void GetApple()
        {
            baseKey = "rBwj1MIAivVN222b";
        }
        private void selectKey(string userName)
        {
//             key12 = baseKey + userName;
//             for (int i = key12.Length; i < 32; i++)
//             {
//                 key12 += "0";
//             }
            key12 = baseKey;
        }
        public string Encrypt(string toEstr, string key)
        {
            string returnstr;
            byte[] toEstrArray = UTF8Encoding.UTF8.GetBytes(toEstr);
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
            AesManaged algorithm = new AesManaged
            {
                Padding = PaddingMode.PKCS7,
                Mode = CipherMode.ECB,
                Key = keyArray
            };
            ICryptoTransform cTransform = algorithm.CreateEncryptor();
            try
            {
                byte[] resultArray = cTransform.TransformFinalBlock(toEstrArray, 0, toEstrArray.Length);
                returnstr = Convert.ToBase64String(resultArray, 0, resultArray.Length);
            }
            catch (CryptographicException ex)
            {
                returnstr = ex.Message;
            }


            return returnstr;
        }
        public string Encrypt(byte[] toEstrArray, string key)
        {
            string returnstr;
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
            AesManaged algorithm = new AesManaged
            {
                Padding = PaddingMode.None,
                Mode = CipherMode.ECB,
                Key = keyArray
            };
            ICryptoTransform cTransform = algorithm.CreateEncryptor();
            try
            {
                byte[] resultArray = cTransform.TransformFinalBlock(toEstrArray, 0, toEstrArray.Length);
                returnstr = Convert.ToBase64String(resultArray, 0, resultArray.Length);
            }
            catch (CryptographicException ex)
            {
                returnstr = ex.Message;
            }


            return returnstr;
        }
        public string Decrypt(string toDstr, string key)
        {
            string returnstr;
            byte[] toDstrArray = Convert.FromBase64String(toDstr);
            returnstr = Decrypt(toDstrArray, key);
            return returnstr;
        }
        public string Decrypt2(string toDstr, string key)
        {
            string returnstr;
            byte[] toDstrArray = Convert.FromBase64String(toDstr);
            returnstr = Decrypt(toDstrArray, key);
            return returnstr;
        }
        public string Decrypt(byte[] toDstrArray, string key)
        {
            string returnstr;
            byte[] keyArray = Encoding.UTF8.GetBytes(key);
            AesManaged algorithm = new AesManaged
            {
                Padding = PaddingMode.PKCS7,
                Mode = CipherMode.ECB,
                Key = keyArray
            };
            int idefo = algorithm.BlockSize;
            ICryptoTransform cTransform = algorithm.CreateDecryptor();
            try
            {
                byte[] resultArray = cTransform.TransformFinalBlock(toDstrArray, 0, toDstrArray.Length);
                returnstr = Encoding.UTF8.GetString(resultArray);
            }
            catch (CryptographicException ex)
            {
                returnstr = ex.Message;
            }
            return returnstr;
        }
        public byte[] DecryptB(byte[] toDstrArray, string key, int i)
        {
            string returnstr;
            byte[] resultArray = null;
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
            AesManaged algorithm = new AesManaged
            {
                Padding = PaddingMode.None,
                Mode = CipherMode.ECB,
                Key = keyArray
            };
            ICryptoTransform cTransform = algorithm.CreateDecryptor();
            try
            {
                resultArray = cTransform.TransformFinalBlock(toDstrArray, 0, i);
                //returnstr = UTF8Encoding.UTF8.GetString(resultArray);
            }
            catch (CryptographicException ex)
            {
                returnstr = ex.Message;
            }
            return resultArray;
        }
        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受  
        }
        bool blogining = false;
        /// <summary>  
        /// 创建POST方式的HTTP请求  
        /// </summary>  
        /// <param name="url">请求的URL</param>  
        /// <param name="parameters">随同请求POST的参数名称及参数值字典</param>  
        /// <param name="timeout">请求的超时时间</param>  
        /// <param name="userAgent">请求的客户端浏览器信息，可以为空</param>  
        /// <param name="requestEncoding">发送HTTP请求时所用的编码</param>  
        /// <param name="cookies">随同HTTP请求发送的Cookie信息，如果不需要身份验证可以为空</param>  
        /// <returns>解码后的XML</returns>  
        public XmlDocument CreatePostHttpResponse(string url, IDictionary<string, string> parameters, int? timeout, string userAgent, Encoding requestEncoding, CookieCollection cookies)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }
            Encoding ec;
            if (requestEncoding == null)
            {
                ec = Encoding.Default;
            }
            else
            {
                ec = requestEncoding;
            }
            HttpWebRequest request = null;
            //如果是发送HTTPS请求  
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request = WebRequest.Create(url) as HttpWebRequest;
                request.ProtocolVersion = HttpVersion.Version11;
            }
            else
            {
                request = WebRequest.Create(url) as HttpWebRequest;
                request.ProtocolVersion = HttpVersion.Version11;
            }
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ServicePoint.Expect100Continue = false;
            if (!string.IsNullOrEmpty(userAgent))
            {
                request.UserAgent = userAgent;
            }
            else
            {
                request.UserAgent = DefaultUserAgent;
            }
            request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
            request.KeepAlive = true;
            if (timeout.HasValue)
            {
                request.Timeout = timeout.Value;
            }
            if (cookies != null)
            {
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(cookies);
            }
            request.Expect = null;
            StringBuilder buffer = new StringBuilder();
            //如果需要POST数据  
            if (!(parameters == null || parameters.Count == 0))
            {
                int i = 0;
                foreach (string key in parameters.Keys)
                {
                    string str = parameters[key].Replace("=", "%3D");
                    str = str.Replace("+", "%2B");
                    str = str.Replace("/", "%2F");
                    if (str.Substring(str.Length - 3) != "%0A")
                    {
                        if (i > 0)
                        {
                            buffer.AppendFormat("&{0}={1}%0A", key, str);
                        }
                        else
                        {
                            buffer.AppendFormat("{0}={1}%0A", key, str);
                        }
                    }
                    else
                    {
                        if (i > 0)
                        {
                            buffer.AppendFormat("&{0}={1}", key, str);
                        }
                        else
                        {
                            buffer.AppendFormat("{0}={1}", key, str);
                        }
                    }
                    i++;
                }

            }
            byte[] data = ec.GetBytes(buffer.ToString());
            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }
            {
                HttpWebResponse hwr = request.GetResponse() as HttpWebResponse;
                Stream st = hwr.GetResponseStream();
                int ilenth = (int)hwr.ContentLength;
                data = null;
                int c1 = 1024 * 400;
                if (ilenth < 0)
                {
                    data = new byte[c1];
                    MemoryStream ms = new MemoryStream();
                    int l = st.Read(data, 0, c1);
                    while (l > 0)
                    {
                        ms.Write(data, 0, l);
                        l = st.Read(data, 0, c1);
                    }
                    data = ms.ToArray();
                    ms.Close();
                }
                else
                {
                    data = new byte[ilenth];
                    int pos = 0;
                    while (ilenth > 0)
                    {
                        int l = st.Read(data, pos, ilenth);
                        pos += l;
                        ilenth -= l;
                    }
                }
                hwr.Close();

                XmlDocument XML1 = null;
                int idata = data.Length;
                try
                {
                    XML1 = new XmlDocument();
                    if (idata == 1408 && url != "http://game1-CBT.ma.sdo.com:10001/connect/app/friend/remove_friend?cyt=1")
                    {
                        szActionLog += "掉线\r\n";
                        if (LoginType == 0&&!blogining)
                        {
                            szActionLog += "自动重连\r\n";
                            blogining = true;
                            if (Login())
                            {
                            }
                            else
                            {
                                szActionLog += "失败\r\n";
                            }
                            Thread.Sleep(5000);

                            blogining = false;
                        }
                        return null;
                    }

                }
                catch (System.Exception ex)
                {

                    return null;
                }
                if (url == "http://game1-CBT.ma.sdo.com:10001/connect/app/mainmenu?cyt=1" || url == "http://game1-CBT.ma.sdo.com:10001/connect/app/regist?cyt=1" || url == "http://game1-CBT.ma.sdo.com:10001/connect/app/tutorial/next?cyt=1" || url == "http://game1-CBT.ma.sdo.com:10001/connect/app/tutorial/save_character?cyt=1" || url == "http://game1-CBT.ma.sdo.com:10001/connect/app/login?cyt=1" || idata == 1408)
                {
                    XML1.LoadXml(Decrypt(data, key0));
                }
                else if (url == "http://game1-CBT.ma.sdo.com:10001/connect/app/friend/remove_friend?cyt=1" || url == "http://game1-CBT.ma.sdo.com:10001/connect/app/friend/add_friend?cyt=1")
                {
                    XML1.LoadXml(Decrypt(data, key11));
                }
                else
                    XML1.LoadXml(Decrypt(data, key12));
                return XML1;
            }
        }

        double dWin = 0;
        
        private int fairybattle(int iU, int iS)
        {
            int iRe = -1;
            //             while (ts.TotalSeconds < 12)
            //             {
            //                 ts = DateTime.Now - dtold1;
            //                 Thread.Sleep(1000);
            //             }
            IDictionary<string, string> parameters = new Dictionary<string, string>()
            {
                {"",""}
            };
            parameters.Clear();
            parameters.Add("serial_id", Encrypt(iS.ToString(), key12));
            parameters.Add("user_id", Encrypt(iU.ToString(), key12));
            string ulr = "http://game1-CBT.ma.sdo.com:10001/connect/app/exploration/fairybattle?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = "game1-CBT.ma.sdo.com";
            cookies.Add(c);
            XmlDocument xml = null;

            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    return iRe;
                }
            }
            bWinner = false;
            if (xml != null)
            {
                string szlogtemp = "战斗：";
                try
                {
                    szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                    if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                    {
                        szlogtemp += xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("message").InnerText + "\r\n";
                        szActionLog += "[" + DateTime.Now.ToString() + "]" + szlogtemp; actionlog.WriteInfo(szlogtemp);
                        iRe = 1001;
                        return iRe;
                    }
                    XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("your_data");//szCharName = node0.SelectSingleNode("name").InnerText + "正在挂机";
                    
                    XmlNode nodeBC = node0.SelectSingleNode("bc");
                    int oldBC = BC;
                    BC = int.Parse(nodeBC.SelectSingleNode("current").InnerText);
                    MaxBc = int.Parse(nodeBC.SelectSingleNode("max").InnerText);
                    XmlNode nodeAP = node0.SelectSingleNode("ap");
                    AP = int.Parse(nodeAP.SelectSingleNode("current").InnerText);
                    MaxAP = int.Parse(nodeAP.SelectSingleNode("max").InnerText);
                    szlogtemp += " BC:" + oldBC.ToString() + "->" + BC.ToString() + " ";
                    int exp1 = int.Parse(xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("battle_result").SelectSingleNode("before_exp").InnerText);
                    int exp2 = int.Parse(xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("battle_result").SelectSingleNode("after_exp").InnerText);
                    bWinner = int.Parse(xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("battle_result").SelectSingleNode("winner").InnerText) == 1;
                    iRe = 0;
                    if (bWinner)
                    {
                        szlogtemp += "-战斗胜利-";
                    }
                    szlogtemp += "经验" + exp1.ToString() + "->" + exp2.ToString();

                    XmlNode noddr = null;
                    try
                    {
                        noddr = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("battle_result").SelectSingleNode("special_item");
                    }
                    catch (System.Exception ex)
                    {
                        szlogtemp += "\r\n";
                    }
                    if (noddr != null)
                    {
                        try
                        {
                            int iitemcount1 = int.Parse(noddr.SelectSingleNode("before_count").InnerText);
                            int iitemcount2 = int.Parse(noddr.SelectSingleNode("after_count").InnerText);


                            szlogtemp += "收集道具：" + (iitemcount2 - iitemcount1).ToString() + "->" + iitemcount2.ToString() + "\r\n";
                        }
                        catch (System.Exception ex)
                        {
                            szlogtemp += "\r\n";
                        }
                    }
                    szActionLog += "[" + DateTime.Now.ToString() + "]" + szlogtemp; actionlog.WriteInfo(szlogtemp);
                }
                catch (System.Exception ex)
                {
                    szlogtemp += ex.Message + "\r\n";
                    szActionLog += "[" + DateTime.Now.ToString() + "]" + szlogtemp; actionlog.WriteInfo(szlogtemp);
                }
            }
            return iRe;
        }

        private int AtacktONE(int iG, int iS, string SK = "dummy")
        {
            int iRe = -1;
            //             while (ts.TotalSeconds < 12)
            //             {
            //                 ts = DateTime.Now - dtold1;
            //                 Thread.Sleep(1000);
            //             }
            IDictionary<string, string> parameters = new Dictionary<string, string>()
            {
                {"",""}
            };
            parameters.Clear();
            parameters.Add("guild_id", Encrypt(iG.ToString(), key12));
            parameters.Add("serial_id", Encrypt(iS.ToString(), key12));
            parameters.Add("spp_skill_serial", Encrypt(SK, key12));
            string ulr = "http://game1-CBT.ma.sdo.com:10001/connect/app/fairy/guild_fairy_battle?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = "game1-CBT.ma.sdo.com";
            cookies.Add(c);
            XmlDocument xml = null;

            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    return iRe;
                }
            }
            bWinner = false;
            if (xml != null)
            {
                string szlogtemp = "战斗：";
                try
                {
                    szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                    if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                    {
                        szlogtemp += xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("message").InnerText + "\r\n";
                        szActionLog += "[" + DateTime.Now.ToString() + "]" + szlogtemp; actionlog.WriteInfo(szlogtemp);
                        iRe = 1001;
                        return iRe;
                    }
                    XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("your_data");//szCharName = node0.SelectSingleNode("name").InnerText + "正在挂机";
                    if (node0 == null)
                    {
                        node0 = xml.SelectSingleNode("response").SelectSingleNode("body");
                        string szName = node0.ChildNodes[0].Name;
                        if (szName == "guild_top" || szName == "guild_defeat_event")
                        {
                            XmlNode node1 = node0.SelectSingleNode(szName).SelectSingleNode("guild_top_update");
                            XmlNode nodd3 = node1.SelectSingleNode("guild_reward_list");
                            if (nodd3 != null && szName == "guild_top")
                            {
                                bBonus = true;
                                string szBX = "";
                                int ibx = int.Parse(nodd3.SelectSingleNode("reward_box_list").SelectSingleNode("box_type").InnerText);
                                switch (ibx)
                                {
                                    case 10101:
                                        szBX = "白金箱";
                                        break;
                                    case 10102:
                                        szBX = "金箱";
                                        break;
                                    case 10103:
                                        szBX = "银箱";
                                        break;
                                    case 10104:
                                        szBX = "铜箱";
                                        break;
                                    case 10105:
                                        szBX = "木箱";
                                        break;
                                }
                                int ibxn = int.Parse(nodd3.SelectSingleNode("reward_box_list").SelectSingleNode("box_num").InnerText);
                                szActionLog += "[" + DateTime.Now.ToString() + "]" + "发现强敌：获得" + szBX + "*" + ibxn.ToString() + "\r\n";
                                actionlog.WriteInfo("发现强敌：获得" + szBX + "*" + ibxn.ToString() + "\r\n");
                            }
                            else if (szName == "guild_defeat_event")
                            {
                                nodd3 = node0.SelectSingleNode(szName).SelectSingleNode("guild_reward_list");
                                if (nodd3.SelectSingleNode("reward_box_list") != null)
                                {
                                    string szBX = "";
                                    int ibx = int.Parse(nodd3.SelectSingleNode("reward_box_list").SelectSingleNode("box_type").InnerText);
                                    switch (ibx)
                                    {
                                        case 10101:
                                            szBX = "白金箱";
                                            break;
                                        case 10102:
                                            szBX = "金箱";
                                            break;
                                        case 10103:
                                            szBX = "银箱";
                                            break;
                                        case 10104:
                                            szBX = "铜箱";
                                            break;
                                        case 10105:
                                            szBX = "木箱";
                                            break;
                                    }
                                    int ibxn = int.Parse(nodd3.SelectSingleNode("reward_box_list").SelectSingleNode("box_num").InnerText);
                                    szActionLog += "[" + DateTime.Now.ToString() + "]" + nodd3 != null ? "强敌已死，获得" + szBX + "*" + ibxn.ToString() + "\r\n" : "强敌已死\r\n";
                                    actionlog.WriteInfo(nodd3 != null ? "强敌已死，获得" + szBX + "*" + ibxn.ToString() + "\r\n" : "强敌已死\r\n");
                                    serial_id = 0;
                                }
                                else
                                {
                                    szActionLog += "[" + DateTime.Now.ToString() + "]" + "强敌已死\r\n";
                                    actionlog.WriteInfo("强敌已死\r\n");
                                }
                            }
                            else
                            {
                                szlogtemp += "新怪\r\n";
                                bBonus = false;
                            }
                            XmlNode node2 = node1.SelectSingleNode("fairy");
                            XmlNode nodeweak = node1.SelectSingleNode("guild_fairy_weak");
                            if (nodeweak != null)
                            {
                                int iweakid = int.Parse(nodeweak.SelectSingleNode("id").InnerText);
                                if (iweakid != iJobID)
                                {
                                    if (-2 != changejob(iweakid)) iJobID = iweakid;
                                }
                            }
                            //master_boss_id = int.Parse(node2.SelectSingleNode("master_boss_id").InnerText);
                            XmlNodeList nodelogs = node1.SelectNodes("guild_log");
//                             szBattleLog = string.Empty;
//                             foreach (XmlNode nodes in nodelogs)
//                             {
//                                 szBattleLog += nodes.SelectSingleNode("log_time").InnerText + " - ";
//                                 szBattleLog += nodes.SelectSingleNode("user_name").InnerText + ":   ";
//                                 szBattleLog += nodes.SelectSingleNode("message").InnerText + "\r\n\r\n";
//                             }
                            serial_id = int.Parse(node2.SelectSingleNode("serial_id").InnerText);
                            lv = int.Parse(node2.SelectSingleNode("lv").InnerText);
                            hp = int.Parse(node2.SelectSingleNode("hp").InnerText);
                            hp_max = int.Parse(node2.SelectSingleNode("hp_max").InnerText);
                            bname = node2.SelectSingleNode("name").InnerText;
                            XmlNode nodef = node1.SelectSingleNode("force_gauge");
                            if (nodef != null)
                            {
                                int iOwn = int.Parse(nodef.SelectSingleNode("own").InnerText);
                                int iRival = int.Parse(nodef.SelectSingleNode("rival").InnerText);
                                int iTotal = int.Parse(nodef.SelectSingleNode("total").InnerText);
                                dWin = (double)(iOwn - iRival) / iTotal / 2;
                            }
                            iGuildID = int.Parse(node2.SelectSingleNode("discoverer_id").InnerText);
                            int timel = int.Parse(node2.SelectSingleNode("time_limit").InnerText);
                            if (node2.SelectSingleNode("master_boss_id") != null)
                            {
                                iRe = 0;
                                if (int.Parse(node2.SelectSingleNode("master_boss_id").InnerText) == iSubBossID)
                                    if (timel > 7080)
                                    {
                                        iRe = 3;
                                    }
                            }
                            else
                            {
                                if (timel > 7080)
                                {
                                    iRe = 3;
                                }
                            }
                            if (szName == "guild_defeat_event")
                            {
                                serial_id = 0;
                                iRe = 2;
                            }
                        }
                        else if (szName == "guild_fairy_event")
                        {
                            iRe = 1;
                        }
                        else if (szName == "guild_top_no_fairy")
                        {
                            iRe = 2;

                            iSubBossID = int.Parse(node0.SelectSingleNode("guild_top_no_fairy").SelectSingleNode("guild_boss").SelectSingleNode("sub_boss_id").InnerText);
                            hp = 0;
                            serial_id = 0;
                        }
                        return iRe;
                    }
                    XmlNode nodeBC = node0.SelectSingleNode("bc");
                    int oldBC = BC;
                    BC = int.Parse(nodeBC.SelectSingleNode("current").InnerText);
                    MaxBc = int.Parse(nodeBC.SelectSingleNode("max").InnerText);
                    XmlNode nodeAP = node0.SelectSingleNode("ap");
                    AP = int.Parse(nodeAP.SelectSingleNode("current").InnerText);
                    MaxAP = int.Parse(nodeAP.SelectSingleNode("max").InnerText);
                    szlogtemp += " BC:" + oldBC.ToString() + "-" + BC.ToString() + " ";
                    iContribution = int.Parse(xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("own_fairy_battle_result").SelectSingleNode("contribution_info").SelectSingleNode("hp_contribution").InnerText);
                    iContribution2 = int.Parse(xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("own_fairy_battle_result").SelectSingleNode("contribution_info").SelectSingleNode("battle_contribution").InnerText);
                    bWinner = int.Parse(xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("own_fairy_battle_result").SelectSingleNode("winner").InnerText) == 1;
                    iRe = 0;
                    if (bWinner)
                    {
                        szlogtemp += "-战斗胜利-";
                    }
                    szlogtemp += "贡献：残血" + iContribution.ToString() + "战斗" + iContribution2.ToString();

                    XmlNodeList noddr = null;
                    try
                    {
                        noddr = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("own_fairy_battle_result").SelectNodes("guild_reward_list");
                    }
                    catch (System.Exception ex)
                    {
                    }
                    if (noddr != null)
                    {
                        try
                        {
                            int iitemcount1 = int.Parse(noddr[0].SelectSingleNode("special_item").SelectSingleNode("before_count").InnerText);
                            int iitemcount2 = int.Parse(noddr[0].SelectSingleNode("special_item").SelectSingleNode("after_count").InnerText);


                            szlogtemp += "收集道具：" + (iitemcount2 - iitemcount1).ToString() + "/" + iitemcount2.ToString() + "\r\n";
                        }
                        catch (System.Exception ex)
                        {
                            szlogtemp += "\r\n";
                        }
                        if (noddr.Count > 1)
                        {
                            bBonus = true;
                            string szBX = "";
                            int ibx = int.Parse(noddr[1].SelectSingleNode("reward_box_list").SelectSingleNode("box_type").InnerText);
                            switch (ibx)
                            {
                                case 10101:
                                    szBX = "白金箱";
                                    break;
                                case 10102:
                                    szBX = "金箱";
                                    break;
                                case 10103:
                                    szBX = "银箱";
                                    break;
                                case 10104:
                                    szBX = "铜箱";
                                    break;
                                case 10105:
                                    szBX = "木箱";
                                    break;
                            }
                            int ibxn = int.Parse(noddr[1].SelectSingleNode("reward_box_list").SelectSingleNode("box_num").InnerText);
                            szlogtemp += "杀死强敌：获得" + szBX + "*" + ibxn.ToString() + "\r\n";
                            serial_id = 0;
                        }
                    }
                    szActionLog += "[" + DateTime.Now.ToString() + "]" + szlogtemp; actionlog.WriteInfo(szlogtemp);

                }
                catch (System.Exception ex)
                {
                    szlogtemp += ex.Message + "\r\n";
                    szActionLog += "[" + DateTime.Now.ToString() + "]" + szlogtemp; actionlog.WriteInfo(szlogtemp);
                }
            }
            return iRe;

        }

        private void ThreadRigist()
        {
            bThreadRigist = true;
            if (bNoLimitedBC)
            {
                while (iNowUserid == 0)
                {
                    iNowUserid = getuserid();
                }
                while (bNoLimitedBC)
                {
                    try
                    {

                        string szPas = "";
                        Guid gu = Guid.NewGuid();

                        byte[] gdata = gu.ToByteArray();
                        if (szPas == "")
                        {
                            for (int j = 9; j < gdata.Length; j++)
                            {
                                szPas += Convert.ToString(gdata[j], 16);
                            }
                        }
                        string szusername = szPas;
                        szcookie = "";
                        try
                        {
                            key11 = baseKey + szusername.Substring(0, 16);
                        }
                        catch (System.Exception ex)
                        {

                            key11 = baseKey + szusername;
                        }
                        for (int i = key11.Length; i < 32; i++)
                        {
                            key11 += "0";
                        }
                        CookieCollection cookies = new CookieCollection();
                        Cookie c = new Cookie("S", szcookie);
                        c.Domain = "game1-CBT.ma.sdo.com";
                        cookies.Add(c);
                        string ulr = "http://game1-CBT.ma.sdo.com:10001/connect/app/regist?cyt=1";
                        IDictionary<string, string> parameters = new Dictionary<string, string>()
                        {
                            {"",""}
                        };
                        parameters.Clear();
                        parameters.Add("login_id", Encrypt(szusername, key0));
                        parameters.Add("password", Encrypt(szPas, key0));
                        string sG = "";
                        for (int j = 8; j < gdata.Length; j++)
                        {
                            sG += Convert.ToString(gdata[j], 16);
                        }
                        parameters.Add("param", Encrypt(sG, key0));

                        XmlDocument xml = null;
                        while (true)
                            try
                            {
                                xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                                break;
                            }
                            catch (System.Exception ex)
                            {
                            }
                        if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                        {
                            continue;
                        }
                        szcookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                        int istep = 100;
                        string szNam = "";
                        c = new Cookie("S", szcookie);
                        c.Domain = "game1-CBT.ma.sdo.com";
                        cookies.Add(c);

                        istep = 100;
                        szNam = "教程" + istep.ToString();
                        ulr = "http://game1-CBT.ma.sdo.com:10001/connect/app/tutorial/next?cyt=1";
                        parameters.Clear();
                        parameters.Add("S", Encrypt(szcookie, key0));
                        parameters.Add("step", Encrypt(istep.ToString(), key0));
                        try
                        {
                            xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);

                        }
                        catch (System.Exception ex)
                        {
                            continue;
                        }

                        istep = 7025;
                        szNam = "教程" + istep.ToString();
                        ulr = "http://game1-CBT.ma.sdo.com:10001/connect/app/tutorial/next?cyt=1";
                        parameters.Clear();
                        parameters.Add("S", Encrypt(szcookie, key0));
                        parameters.Add("step", Encrypt(istep.ToString(), key0));
                        try
                        {
                            xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);

                        }
                        catch (System.Exception ex)
                        {
                            continue;
                        }


                        istep = 8000;
                        szNam = "教程" + istep.ToString() + "教程完成";
                        parameters.Clear();
                        parameters.Add("S", Encrypt(szcookie, key0));
                        parameters.Add("step", Encrypt("8000", key0));

                        try
                        {
                            xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);

                        }
                        catch (System.Exception ex)
                        {
                            continue;
                        }

                        if (xml == null)
                        {
                            continue;
                        }

                        szcookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;

                        XmlNode node1 = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("login").SelectSingleNode("user_id");
                        int iUserid = int.Parse(node1.InnerText);


                        c = new Cookie("S", szcookie);
                        c.Domain = "game1-CBT.ma.sdo.com";
                        cookies.Add(c);

                        ulr = "http://game1-CBT.ma.sdo.com:10001/connect/app/friend/add_friend?cyt=1";
                        while (true)
                            try
                            {
                                parameters.Clear();
                                parameters.Add("dialog", Encrypt("1", key11));
                                parameters.Add("user_id", Encrypt(iNowUserid.ToString(), key11));
                                xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                                break;
                            }
                            catch (System.Exception ex)
                            {
                            }


                        alowuser(iUserid);
                        setbc();

                        c = new Cookie("S", szcookie);
                        c.Domain = "game1-CBT.ma.sdo.com";
                        cookies.Add(c);
                        int i2 = 0;
                        ulr = "http://game1-CBT.ma.sdo.com:10001/connect/app/friend/remove_friend?cyt=1";
                        while (true)
                            try
                            {
                                parameters.Clear();
                                parameters.Add("dialog", Encrypt("1", key11));
                                parameters.Add("user_id", Encrypt(iNowUserid.ToString(), key11));
                                xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                                break;
                            }
                            catch (System.Exception ex)
                            {
                                i2++;
                                if (i2 > 5)
                                {
                                    break;
                                }
                            }
                        bActNoLimit = false;
                    }
                    catch (System.Exception ex)
                    {

                    }
                }
            }
            bThreadRigist = true;
        }

        private int alowuser(int iuser)
        {
            string ulr = "http://game1-CBT.ma.sdo.com:10001/connect/app/friend/approve_friend?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = "game1-CBT.ma.sdo.com";
            cookies.Add(c);
            IDictionary<string, string> parameters = new Dictionary<string, string>()
                    {
                        {"",""}
                    };
            parameters.Clear();
            parameters.Add("dialog", Encrypt("1", key12));
            parameters.Add("user_id", Encrypt(iuser.ToString(), key12));

            XmlDocument xml = null;
            try
            {
                xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);

            }
            catch (System.Exception ex)
            {
                return -1;
            }
            if (xml != null)
            {
                if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                {
                    string errormessage = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("message").InnerText + "\r\n";
                    szActionLog += "[" + DateTime.Now.ToString() + "]" + errormessage; 
                    return -1;
                }
                szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;

            }
            return 0;
        }

        private void setbc()
        {
            string ulr = "http://game1-CBT.ma.sdo.com:10001/connect/app/town/pointsetting?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = "game1-CBT.ma.sdo.com";
            cookies.Add(c);
            IDictionary<string, string> parameters = new Dictionary<string, string>()
                    {
                        {"",""}
                    };
            parameters.Clear();
            if (bxiap)
            {
                parameters.Add("ap", Encrypt("3", key12));
                parameters.Add("bc", Encrypt("0", key12));
            }
            else
            {
                parameters.Add("ap", Encrypt("0", key12));
                parameters.Add("bc", Encrypt("3", key12));
            }

            XmlDocument xml = null;
            while (true)
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                }
            if (xml != null)
            {
                if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                {
                    string errormessage = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("message").InnerText + "\r\n";
                    szActionLog += "[" + DateTime.Now.ToString() + "]" + errormessage; 
                    return;
                }
                szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("your_data"); szCharName = node0.SelectSingleNode("name").InnerText + "正在挂机";

                XmlNode nodeBC = node0.SelectSingleNode("bc");
                BC = int.Parse(nodeBC.SelectSingleNode("current").InnerText);

                MaxBc = int.Parse(nodeBC.SelectSingleNode("max").InnerText);
                XmlNode nodeAP = node0.SelectSingleNode("ap");
                AP = int.Parse(nodeAP.SelectSingleNode("current").InnerText);
                MaxAP = int.Parse(nodeAP.SelectSingleNode("max").InnerText);
            }
        }
        int nowFairyID = 0;
        List<int> fairylist = new List<int>();
        private int getFairyIfo()
        {
            int iReturn = -1;
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = "game1-CBT.ma.sdo.com";
            cookies.Add(c);
            string ulr = "http://game1-CBT.ma.sdo.com:10001/connect/app/menu/fairyselect?cyt=1";
            XmlDocument xml = null;
            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, null, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue; ;
                }
            }
            try
            {
                XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("fairy_select");
                XmlNodeList nodefairies = node0.SelectNodes("fairy_event");
                bool bg = true;
                foreach (XmlNode nodes in nodefairies)
                {
                    string szUser = nodes.SelectSingleNode("user").SelectSingleNode("name").InnerText;
                    int iuserid = int.Parse(nodes.SelectSingleNode("user").SelectSingleNode("id").InnerText);
                    string szboss = nodes.SelectSingleNode("fairy").SelectSingleNode("name").InnerText;
                    int iserialid = int.Parse(nodes.SelectSingleNode("fairy").SelectSingleNode("serial_id").InnerText);
                    int lv = int.Parse(nodes.SelectSingleNode("fairy").SelectSingleNode("lv").InnerText);
                    bool balive = int.Parse(nodes.SelectSingleNode("put_down").InnerText) == 1;
                    if (iuserid == iNowUserid)
                    {
                        if (balive)
                        {
                            bg = false;
                        }
                    }
                    if (balive)
                    {
                        if (!fairylist.Contains(iserialid) || BC == MaxBc)
                        {
                            szActionLog += "攻击：" + szUser + "-lv" + lv.ToString() + szboss + "\r\n";
                            if (1001 == fairybattle(iuserid, iserialid))
                            {
                                break;
                            }
                            else
                            {
                                fairylist.Add(iserialid);
                                if (fairylist.Count > 30)
                                {
                                    fairylist.RemoveAt(0);
                                }
                                Thread.Sleep(10000);
                            }
                        }
                    }
                }
                bExplore = bg;
            }
            catch (System.Exception ex)
            {
                serial_id = 0;
            }
            return iReturn;
        }
        private int getGuidIFO()
        {
            int iReturn = -1;
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = "game1-CBT.ma.sdo.com";
            cookies.Add(c);
            string ulr = "http://game1-CBT.ma.sdo.com:10001/connect/app/guild/guild_top?cyt=1";

            XmlDocument xml = null;
            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, null, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue; ;
                }
            }
            try
            {
                XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("body");
                string szName = node0.ChildNodes[0].Name;
                if (szName == "guild_top" || szName == "guild_defeat_event")
                {
                    XmlNode node1 = node0.SelectSingleNode(szName).SelectSingleNode("guild_top_update");
                    XmlNode nodd3 = node1.SelectSingleNode("guild_reward_list");
                    if (nodd3 != null && szName == "guild_top")
                    {
                        bBonus = true;
                        string szBX = "";
                        int ibx = int.Parse(nodd3.SelectSingleNode("reward_box_list").SelectSingleNode("box_type").InnerText);
                        switch (ibx)
                        {
                            case 10101:
                                szBX = "白金箱";
                                break;
                            case 10102:
                                szBX = "金箱";
                                break;
                            case 10103:
                                szBX = "银箱";
                                break;
                            case 10104:
                                szBX = "铜箱";
                                break;
                            case 10105:
                                szBX = "木箱";
                                break;
                        }
                        int ibxn = int.Parse(nodd3.SelectSingleNode("reward_box_list").SelectSingleNode("box_num").InnerText);
                        szActionLog += "[" + DateTime.Now.ToString() + "]" + "发现强敌：获得" + szBX + "*" + ibxn.ToString() + "\r\n";
                        actionlog.WriteInfo("发现强敌：获得" + szBX + "*" + ibxn.ToString() + "\r\n");
                    }
                    else if (szName == "guild_defeat_event")
                    {
                        nodd3 = node0.SelectSingleNode(szName).SelectSingleNode("guild_reward_list");
                        string szBX = "";
                        int ibx = int.Parse(nodd3.SelectSingleNode("reward_box_list").SelectSingleNode("box_type").InnerText);
                        switch (ibx)
                        {
                            case 10101:
                                szBX = "白金箱";
                                break;
                            case 10102:
                                szBX = "金箱";
                                break;
                            case 10103:
                                szBX = "银箱";
                                break;
                            case 10104:
                                szBX = "铜箱";
                                break;
                            case 10105:
                                szBX = "木箱";
                                break;
                        }
                        int ibxn = int.Parse(nodd3.SelectSingleNode("reward_box_list").SelectSingleNode("box_num").InnerText);
                        szActionLog += "[" + DateTime.Now.ToString() + "]" + nodd3 != null ? "强敌已死，获得" + szBX + "*" + ibxn.ToString() + "\r\n" : "强敌已死\r\n";
                        actionlog.WriteInfo(nodd3 != null ? "强敌已死，获得" + szBX + "*" + ibxn.ToString() + "\r\n" : "强敌已死\r\n");
                    }
                    else
                    {
                        bBonus = false;
                    }
                    XmlNode node2 = node1.SelectSingleNode("fairy");
//                     XmlNode nodeweak = node1.SelectSingleNode("guild_fairy_weak");
//                     if (nodeweak != null)
//                     {
//                         int iweakid = int.Parse(nodeweak.SelectSingleNode("id").InnerText);
//                         if (iweakid != iJobID)
//                         {
//                             if (-2 != changejob(iweakid)) iJobID = iweakid;
//                         }
//                     }
                    XmlNodeList nodelogs = node1.SelectNodes("guild_log");
                    //                     szBattleLog = string.Empty;
                    //                     foreach (XmlNode nodes in nodelogs)
                    //                     {
                    //                         szBattleLog += nodes.SelectSingleNode("log_time").InnerText + " - ";
                    //                         szBattleLog += nodes.SelectSingleNode("user_name").InnerText + ":   ";
                    //                         szBattleLog += nodes.SelectSingleNode("message").InnerText + "\r\n\r\n";
                    //                     }
                    serial_id = int.Parse(node2.SelectSingleNode("serial_id").InnerText);
                    lv = int.Parse(node2.SelectSingleNode("lv").InnerText);
                    hp = int.Parse(node2.SelectSingleNode("hp").InnerText);
                    hp_max = int.Parse(node2.SelectSingleNode("hp_max").InnerText);
                    bname = node2.SelectSingleNode("name").InnerText;
                    XmlNode nodef = node1.SelectSingleNode("force_gauge");
                    if (nodef != null)
                    {
                        int iOwn = int.Parse(nodef.SelectSingleNode("own").InnerText);
                        int iRival = int.Parse(nodef.SelectSingleNode("rival").InnerText);
                        int iTotal = int.Parse(nodef.SelectSingleNode("total").InnerText);
                        dWin = (double)(iOwn - iRival) / iTotal / 2;
                    }
                    iGuildID = int.Parse(node2.SelectSingleNode("discoverer_id").InnerText);
                    int timel = int.Parse(node2.SelectSingleNode("time_limit").InnerText);
                    szActionLog += "刷新boss："+ bname + "__Lv:" + lv + "__HP" + hp + "/" + hp_max + "\r\n"; 
                    iReturn = 0;
                    if (int.Parse(node2.SelectSingleNode("master_boss_id").InnerText) == iSubBossID)
                    {
                        bSub = true;
                        if (timel > 7080 || (DateTime.Now.Hour > 23 || DateTime.Now.Hour < 1))
                        {
                            iReturn = 3;
                        }
                    }
                    else if (iSubBossID == 0 && hp_max < 1000000)
                    {
                        iSubBossID = int.Parse(node2.SelectSingleNode("master_boss_id").InnerText);
                        bSub = true;
                        if (timel > 7080 || (DateTime.Now.Hour > 23 || DateTime.Now.Hour < 1))
                        {
                            iReturn = 3;
                        }
                    }
                    else
                    {
                        bSub = false;
                    }
                    
                    if (szName == "guild_defeat_event")
                    {
                        iReturn = 2;
                    }
                }
                else if (szName == "guild_fairy_event")
                {
                    iReturn = 1;
                    szActionLog += "强敌出现\r\n";
                }
                else if (szName == "guild_top_no_fairy")
                {
                    iReturn = 2;

                    master_boss_id = int.Parse(node0.SelectSingleNode("guild_top_no_fairy").SelectSingleNode("guild_boss").SelectSingleNode("master_boss_id").InnerText);
                    iSubBossID = int.Parse(node0.SelectSingleNode("guild_top_no_fairy").SelectSingleNode("guild_boss").SelectSingleNode("sub_boss_id").InnerText);
                    hp = 0;
                    serial_id = 0;
                }
            }
            catch (System.Exception ex)
            {
                serial_id = 0;
            }
            return iReturn;
        }
        private int getRankINFO()
        {
            int iRe = -1;
            IDictionary<string, string> parameters = new Dictionary<string, string>()
            {
                {"",""}
            };
            parameters.Clear();
            string ulr = "http://game1-CBT.ma.sdo.com:10001/connect/app/guild/guild_info?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = "game1-CBT.ma.sdo.com";
            cookies.Add(c);
            XmlDocument xml = null;

            try
            {
                xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
            }
            catch (System.Exception ex)
            {
                return -1;
            }
            if (xml == null)
            {
                return -1;
            }

            if (xml != null)
            {
                try
                {
                    if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                    {
                        return iRe;
                    }
                    szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                    XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("guild_info");
                    labelgrk = node0.SelectSingleNode("user_rank").InnerText;
                    labelgzg = node0.SelectSingleNode("user_hunting_point").InnerText;
                    labelzzg = node0.SelectSingleNode("guild_hunting_point").SelectSingleNode("own_guild_point").InnerText;
                    labelzrg = node0.SelectSingleNode("guild_hunting_point").SelectSingleNode("own_guild_dairy_point").InnerText;
                    labelzrk = node0.SelectSingleNode("own_guild_rank").InnerText;
                    labelxzg = node0.SelectSingleNode("guild_hunting_point").SelectSingleNode("rival_guild_point").InnerText;
                    labelxrg = node0.SelectSingleNode("guild_hunting_point").SelectSingleNode("rival_guild_dairy_point").InnerText;
                    labelxrk = node0.SelectSingleNode("rival_guild_rank").InnerText;

                }
                catch (System.Exception ex)
                {
                }
            }
            return iRe;
        }

        private int changejob(int i)
        {
            IDictionary<string, string> parameters = new Dictionary<string, string>()
            {
                {"",""}
            };
            parameters.Clear();
            parameters.Add("jid", Encrypt(i.ToString(), key12));
            string ulr = "http://game1-CBT.ma.sdo.com:10001/connect/app/job/change_job?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = "game1-CBT.ma.sdo.com";
            cookies.Add(c);
            XmlDocument xml = null;
            string szname;
            switch (i)
            {
                case 1:
                    szname = "士兵|" + lv;
                    break;
                case 2:
                    szname = "武斗|" + lv;
                    break;
                case 3:
                    szname = "操纵|" + lv;
                    break;
                case 4:
                    szname = "弓手|" + lv;
                    break;
                case 5:
                    szname = "风水|" + lv;
                    break;
                case 6:
                    szname = "曜魔|" + lv;
                    break;
                case 7:
                    szname = "会长|" + lv;
                    break;
                case 8:
                    szname = "妹|" + lv;
                    break;
                default:
                    szname = "??|" + lv;
                    break;
            }
            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    return -2;
                }
            }
            if (xml != null)
            {
                if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) == 0)
                {
                    return -1;
                }
                szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                szActionLog += "更换职业：" + szname + "\r\n";
            }
            return 0;
        }
        private int sellcard(string str)
        {
            IDictionary<string, string> parameters = new Dictionary<string, string>()
            {
                {"",""}
            };
            parameters.Clear();
            parameters.Add("serial_id", Encrypt(str, key12));
            string ulr = "http://game1-CBT.ma.sdo.com:10001/connect/app/trunk/sell?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = "game1-CBT.ma.sdo.com";
            cookies.Add(c);
            XmlDocument xml = null;

            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue;
                }
            }
            if (xml != null)
            {
                if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) == 8000)
                {
                    return 0;
                }
                szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("your_data"); szCharName = node0.SelectSingleNode("name").InnerText;
                XmlNode nodeBC = node0.SelectSingleNode("bc");
                BC = int.Parse(nodeBC.SelectSingleNode("current").InnerText);
                MaxBc = int.Parse(nodeBC.SelectSingleNode("max").InnerText);
                XmlNode nodeAP = node0.SelectSingleNode("ap");
                AP = int.Parse(nodeAP.SelectSingleNode("current").InnerText);
                MaxAP = int.Parse(nodeAP.SelectSingleNode("max").InnerText);
                XmlNodeList nodeCardlist = node0.SelectSingleNode("owner_card_list").SelectNodes("user_card");


                if (nodeCardlist != null && nodeCardlist.Count != 0)
                {
                    cardlist = nodeCardlist;
                    szActionLog += "卖卡成功-卡数:" + nodeCardlist.Count + "\r\n\r\n";
                }
                if (nodeCardlist.Count >= 190)
                {
                    return -1;
                }
            }
            return 0;
        }
        private int getRewards(string strr)
        {
            IDictionary<string, string> parameters = new Dictionary<string, string>()
            {
                {"",""}
            };
            parameters.Clear();
            parameters.Add("notice_id", Encrypt(strr, key12));
            string ulr = "http://game1-CBT.ma.sdo.com:10001/connect/app/menu/get_rewards?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = "game1-CBT.ma.sdo.com";
            cookies.Add(c);
            XmlDocument xml = null;

            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue;
                }
            }
            if (xml != null)
            {
//                 if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
//                 {
//                     return 0;
//                 }

                szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("your_data");
                if (node0 == null)
                {
                    return -1;
                }
                szCharName = node0.SelectSingleNode("name").InnerText;
                XmlNode nodeBC = node0.SelectSingleNode("bc");
                BC = int.Parse(nodeBC.SelectSingleNode("current").InnerText);
                MaxBc = int.Parse(nodeBC.SelectSingleNode("max").InnerText);
                XmlNode nodeAP = node0.SelectSingleNode("ap");
                AP = int.Parse(nodeAP.SelectSingleNode("current").InnerText);
                MaxAP = int.Parse(nodeAP.SelectSingleNode("max").InnerText);
                string strsell = "";
                XmlNodeList nodeCardlist = null;
                int isellnum = 0;

                nodeCardlist = node0.SelectSingleNode("owner_card_list").SelectNodes("user_card");
                
                if (nodeCardlist != null && nodeCardlist.Count != 0)
                {
                    cardlist = nodeCardlist;
                    szActionLog += "收箱-卡数:" + nodeCardlist.Count + "\r\n";
                }
                string szSellid = "卖：\r\n";
                foreach (XmlNode nodes in nodeCardlist)
                {
                    int icardlv = int.Parse(nodes.SelectSingleNode("lv").InnerText);
                    int icardlvmax = int.Parse(nodes.SelectSingleNode("lv_max").InnerText);
                    int icardsale_price = int.Parse(nodes.SelectSingleNode("sale_price").InnerText);
                    int icardhp = int.Parse(nodes.SelectSingleNode("hp").InnerText);
                    int icardpower = int.Parse(nodes.SelectSingleNode("power").InnerText);
                    int iHolo = int.Parse(nodes.SelectSingleNode("holography").InnerText);
                    if (icardlv == 1)
                    {
                        if ((icardhp > 1 || icardpower > 1) && iHolo == 0 && icardlvmax < 50)
                        {
                            if (icardsale_price < iSellPrice)
                            {
                                if (isellnum == 0)
                                {
                                    strsell += nodes.SelectSingleNode("serial_id").InnerText;
                                }
                                else
                                {
                                    strsell += "," + nodes.SelectSingleNode("serial_id").InnerText;
                                }
                                szSellid +="ID:" + nodes.ChildNodes[1].InnerText + " lv:" + icardlv + "/" + icardlvmax + "  atk/hp:" + icardpower + "/" + icardhp + "\r\n";
                                isellnum++;
                            }
                        }
                    }
                    else if (icardlvmax < 50&&icardlv < 30)
                    {
                        if (isellnum == 0)
                        {
                            strsell += nodes.SelectSingleNode("serial_id").InnerText;
                        }
                        else
                        {
                            strsell += "," + nodes.SelectSingleNode("serial_id").InnerText;
                        }
                        szSellid += "ID:" + nodes.ChildNodes[1].InnerText + " lv:" + icardlv + "//" + icardlvmax + "  atk/hp:" + icardpower + "//" + icardhp + "\r\n";
                        isellnum++;
                    }
                    if (isellnum == 30)
                    {
                        szActionLog += szSellid + "\r\n";
                        if (-1 == sellcard(strsell)) return -1;
                        isellnum = 0;
                        strsell = "";
                        szSellid = "卖：\r\n";
                    }
                }
                if (strsell != "")
                {
                    szActionLog += szSellid;
                    if (-1 == sellcard(strsell)) return -1;
                }
            }
            return 0;
        }
        private int getRewardsAll()
        {
            IDictionary<string, string> parameters = new Dictionary<string, string>()
            {
                {"",""}
            };
            parameters.Clear();
            string ulr = "http://game1-CBT.ma.sdo.com:10001/connect/app/menu/rewardbox?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = "game1-CBT.ma.sdo.com";
            cookies.Add(c);
            XmlDocument xml = null;

            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue;
                }
            }
            if (xml != null)
            {
                if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                {
                    return -1;
                }
                szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                XmlNode node0 = null;

                XmlNodeList nodeboxs = null;
                try
                {
                    node0 = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("rewardbox_list");

                    nodeboxs = node0.SelectNodes("rewardbox");
                }
                catch (System.Exception ex)
                {
                    return -1;
                }
                if (nodeboxs == null)
                {
                    return -1;
                }
                else if (nodeboxs.Count == 0)
                {
                    return -1;
                }
                string strbox = "";
                int i = 0;
                szActionLog += "礼物箱"+nodeboxs.Count+"\r\n";
                foreach (XmlNode nodes in nodeboxs)
                {
                    if (i == 0)
                    {
                        strbox += nodes.SelectSingleNode("id").InnerText;
                    }
                    else
                    {
                        strbox += "," + nodes.SelectSingleNode("id").InnerText;
                    }
                    i++;
                }
                return getRewards(strbox);
            }
            return -1;
        }

        private int getuserid()
        {
            int iUserid = 0;
            string ulr = "http://game1-CBT.ma.sdo.com:10001/connect/app/mainmenu?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = "game1-CBT.ma.sdo.com";
            cookies.Add(c);
            IDictionary<string, string> parameters = new Dictionary<string, string>()
                    {
                        {"",""}
                    };
            parameters.Clear();
            parameters.Add("ap", Encrypt("0", key12));
            parameters.Add("bc", Encrypt("3", key12));

            XmlDocument xml = null;
            try
            {
                xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);

            }
            catch (System.Exception ex)
            {
                return 0;
            }
            if (xml != null)
            {
                if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                {
                    return 0;
                }
                szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("your_data"); szCharName = node0.SelectSingleNode("name").InnerText;

                XmlNode nodeBC = node0.SelectSingleNode("bc");
                BC = int.Parse(nodeBC.SelectSingleNode("current").InnerText);

                MaxBc = int.Parse(nodeBC.SelectSingleNode("max").InnerText);
                XmlNode nodeAP = node0.SelectSingleNode("ap");
                AP = int.Parse(nodeAP.SelectSingleNode("current").InnerText);
                MaxAP = int.Parse(nodeAP.SelectSingleNode("max").InnerText);
                XmlNode node1 = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("login").SelectSingleNode("user_id");
                iUserid = int.Parse(node1.InnerText);
                //iPartyid = int.Parse(node0.SelectSingleNode("party_id").InnerText);
                szActionLog += "登录成功\r\ncookie:" + szCookie + "|user:" + iUserid.ToString() + "|name:" + szCharName + "\r\n";
            }
            return iUserid;
        }
        private int getapbc()
        {
            if (iAreaID == 0)
            {
                GetAreaIfo();
            }
            IDictionary<string, string> parameters = new Dictionary<string, string>()
            {
                {"",""}
            };
            parameters.Clear();
            string s1 = "1";
            parameters.Add("area_id", Encrypt(iAreaID.ToString(), key12));
            parameters.Add("check", Encrypt(s1.ToString(), key12));
            parameters.Add("floor_id", Encrypt(szFloor.ToString(), key12));
            string ulr = "http://game1-CBT.ma.sdo.com:10001/connect/app/exploration/get_floor?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = "game1-CBT.ma.sdo.com";
            cookies.Add(c);
            XmlDocument xml = null;

            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue;
                }
            }
            if (xml != null)
            {
                if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                {
//                     if (bAutoChange)
//                     {
//                         iAreaID--;
//                         szFloor = "1";
//                         bAutoChange = false;
//                     }
//                     else
//                     {
//                         iAreaID = 0;
//                         szFloor = "1";
//                     }
                    return 0;
                }
                szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("your_data"); szCharName = node0.SelectSingleNode("name").InnerText;

                XmlNode nodeBC = node0.SelectSingleNode("bc");
                BC = int.Parse(nodeBC.SelectSingleNode("current").InnerText);

                MaxBc = int.Parse(nodeBC.SelectSingleNode("max").InnerText);
                XmlNode nodeAP = node0.SelectSingleNode("ap");
                AP = int.Parse(nodeAP.SelectSingleNode("current").InnerText);
                MaxAP = int.Parse(nodeAP.SelectSingleNode("max").InnerText);
                XmlNode node1 = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("get_floor");
                ilowap = int.Parse(node1.SelectSingleNode("floor_info").SelectSingleNode("cost").InnerText);
                AreaName = node1.SelectSingleNode("area_name").InnerText;

                XmlNode nodeg = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("guild_fairy_state");
                int ire = 0;
                if (nodeg != null)
                {
                    ire = int.Parse(nodeg.SelectSingleNode("fairy_state").InnerText);
                }
                return ire;
            }
            else
            {
                return 0;
            }
        }


        private void useitem(int iD)
        {
            IDictionary<string, string> parameters = new Dictionary<string, string>()
            {
                {"",""}
            };
            parameters.Clear();
            parameters.Add("item_id", Encrypt(iD.ToString(), key12));
            string ulr = "http://game1-CBT.ma.sdo.com:10001/connect/app/item/use?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = "game1-CBT.ma.sdo.com";
            cookies.Add(c);
            XmlDocument xml = null;

            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue;
                }
            }
            if (xml != null)
            {
                try
                {
                    if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                    {
                        //GetAreaIfo();
                        string errormessage = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("message").InnerText + "\r\n";
                        szActionLog += "[" + DateTime.Now.ToString() + "]" + errormessage; actionlog.WriteInfo(errormessage);

                    }
                    szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                    XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("your_data"); szCharName = node0.SelectSingleNode("name").InnerText;
                    XmlNode nodeBC = node0.SelectSingleNode("bc");
                    BC = int.Parse(nodeBC.SelectSingleNode("current").InnerText);
                    MaxBc = int.Parse(nodeBC.SelectSingleNode("max").InnerText);
                    XmlNode nodeAP = node0.SelectSingleNode("ap");
                    AP = int.Parse(nodeAP.SelectSingleNode("current").InnerText);
                    MaxAP = int.Parse(nodeAP.SelectSingleNode("max").InnerText);


                }
                catch (System.Exception ex)
                {
                    szActionLog += "[" + DateTime.Now.ToString() + "]" + ex.Message + "\r\n"; actionlog.WriteInfo(ex.Message + "\r\n");
                }
            }
        }
        bool bAtoBuild = true;
        int imaicount = 0;


        private int explore()
        {
            int iRe = -1;
            int ire = 0;
            if (iAreaID == 0)
            {
                GetAreaIfo();
            }
            IDictionary<string, string> parameters = new Dictionary<string, string>()
            {
                {"",""}
            };
            parameters.Clear();
            bAtoBuild = checkBox5.Checked;
            string s1 = bAtoBuild ? "1" : "0";
            parameters.Add("area_id", Encrypt(iAreaID.ToString(), key12));
            parameters.Add("auto_build", Encrypt(s1.ToString(), key12));
            parameters.Add("floor_id", Encrypt(szFloor, key12));
            string ulr = "http://game1-CBT.ma.sdo.com:10001/connect/app/exploration/explore?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = "game1-CBT.ma.sdo.com";
            cookies.Add(c);
            XmlDocument xml = null;

            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue;
                }
            }
            if (xml != null)
            {
                string szLogTemp = "移动：";
                try
                {
                    XmlNode ereaNode = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("exploration_area");
                    if (ereaNode != null)
                    {
                        if (!bliqu) return ire;
                        XmlNodeList erarlist = ereaNode.SelectSingleNode("area_info_list").SelectNodes("area_info");
                        iAreaID = int.Parse(erarlist[0].SelectSingleNode("id").InnerText);
                        AreaName = erarlist[0].SelectSingleNode("name").InnerText;
                        if (!bAutoChange)
                        {
                            foreach (XmlNode enodes in erarlist)
                            {
                                int inowid = int.Parse(enodes.SelectSingleNode("id").InnerText);
                                if (iAreaID / 100 == inowid / 100)
                                {
                                    iAreaID = inowid;
                                    AreaName = enodes.SelectSingleNode("name").InnerText;
                                }
                            }
                        }
                        szFloor = "1";
                        szLogTemp += "里表区切换 ; ";
                        if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                        {
                            //GetAreaIfo();
                            szLogTemp += xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("message").InnerText + "\r\n";

                        }

                        szActionLog += "[" + DateTime.Now.ToString() + "]" + szLogTemp; actionlog.WriteInfo(szLogTemp);

                        return ire;
                    }
                    if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                    {
                        //GetAreaIfo();
                        szLogTemp += xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("message").InnerText + "\r\n";
                        szActionLog += "[" + DateTime.Now.ToString() + "]" + szLogTemp; actionlog.WriteInfo(szLogTemp);

                        return ire;
                    }
                    szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                    XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("your_data"); szCharName = node0.SelectSingleNode("name").InnerText;
                    XmlNode nodeBC = node0.SelectSingleNode("bc");
                    int oldAp = AP;
                    int oldBC = BC;
                    BC = int.Parse(nodeBC.SelectSingleNode("current").InnerText);
                    MaxBc = int.Parse(nodeBC.SelectSingleNode("max").InnerText);
                    XmlNode nodeAP = node0.SelectSingleNode("ap");
                    AP = int.Parse(nodeAP.SelectSingleNode("current").InnerText);
                    MaxAP = int.Parse(nodeAP.SelectSingleNode("max").InnerText);
                    iRe = int.Parse(xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("explore").SelectSingleNode("event_type").InnerText);

                    int iPorgress = int.Parse(xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("explore").SelectSingleNode("progress").InnerText);
                    //((ComboBoxItem)comboBox3.SelectedItem).Text = "区域" + szFloor + "|" + ilowap.ToString() + "|" + iPorgress.ToString();
                    XmlNode nodecard = node0.SelectSingleNode("owner_card_list");
                    if (nodecard != null)
                    {
                        XmlNodeList xmllist = nodecard.SelectNodes("user_card");
                        if(xmllist.Count != 0)
                            cardlist = xmllist;
                    }
                    XmlNode nodeg = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("guild_fairy_state");

                    if (nodeg != null)
                    {
                        ire = int.Parse(nodeg.SelectSingleNode("fairy_state").InnerText);
                    }
                    szLogTemp += AreaName + "|" + szFloor + "|" + ilowap + "|" + iPorgress + "-";
                    string szBoss = "";
                    if (iRe == 1)
                    {
                        bExplore = false;
                        XmlNode fairyNode = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("explore").SelectSingleNode("fairy");
                        iMasterBossID = int.Parse(fairyNode.SelectSingleNode("serial_id").InnerText);
                        
                        szBoss = "lv" + fairyNode.SelectSingleNode("lv").InnerText + fairyNode.SelectSingleNode("name").InnerText + " HP:" + fairyNode.SelectSingleNode("hp").InnerText;
                    }

                    switch (iRe)
                    {
                        case 1:
                            szLogTemp += "发现妖精" + szBoss;
                            break;
                        case 3:
                            szLogTemp += "发现卡片";
                            break;
                        case 15:
                            szLogTemp += "合成卡片";
                            break;
                        case 6:
                            szLogTemp += "AP不足";
                            break;
                        case 12:
                            szLogTemp += "AP回复";
                            break;
                        case 13:
                            szLogTemp += "BC回复";
                            break;
                        case 19:
                            szLogTemp += "发现道具";
                            break;
                        default:
                            szLogTemp += "事件ID:" + iRe.ToString();
                            break;
                    }
                    szLogTemp += "  AP:" + oldAp.ToString() + "-" + AP.ToString() + " BC:" + oldBC.ToString() + "-" + BC.ToString() + "\r\n";
                    szActionLog += "[" + DateTime.Now.ToString() + "]" + szLogTemp; actionlog.WriteInfo(szLogTemp);

                    if (iPorgress == 100)
                    {
                        XmlNode nodenext = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("explore").SelectSingleNode("next_floor");
                        if (nodenext != null && comboBox3.SelectedIndex == comboBox3.Items.Count - 1)
                        {
                            GetFloorIfo();
                            comboBox3.SelectedIndex = comboBox3.Items.Count - 2;
                        }
                        if (bAutoChange)
                        {
                            if (nodenext != null)
                            {
                                comboBox3.SelectedIndex = comboBox3.Items.Count - 1;
                            }
                            else
                            {
                                GetAreaIfo();
                            }
                        }
                    }
                }
                catch (System.Exception ex)
                {
                    szLogTemp += ex.Message + "\r\n";
                    szActionLog += "[" + DateTime.Now.ToString() + "]" + szLogTemp; actionlog.WriteInfo(szLogTemp);
                }

            }
            return iRe;
        }

        private void MessageBox(string p)
        {
            throw new NotImplementedException();
        }

        private void UpdateJob()
        {
            string ulr = "http://game1-CBT.ma.sdo.com:10001/connect/app/job/job_top?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = "game1-CBT.ma.sdo.com";
            cookies.Add(c);
            XmlDocument xml = null;

            szActionLog += "更新职业\r\n";
            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, null, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue;
                }
            }
            areaxml = xml;
            if (xml != null)
            {
                XmlNode node1 = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("job_top");
                XmlNodeList jobs = node1.SelectNodes("job_states");
                iJobID = int.Parse(node1.SelectSingleNode("equipping_job_id").InnerText);
                comboBox2.Items.Clear();
                ComboBoxItem cbis = null;
                int iindex = 0;
                foreach (XmlNode nodes in jobs)
                {
                    int id = int.Parse(nodes.SelectSingleNode("job_id").InnerText);
                    int lv = int.Parse(nodes.SelectSingleNode("job_lv").InnerText);
                    string szname;
                    switch (id)
                    {
                        case 1:
                            szname = "士兵|" + lv;
                            break;
                        case 2:
                            szname = "武斗|" + lv;
                            break;
                        case 3:
                            szname = "操纵|" + lv;
                            break;
                        case 4:
                            szname = "弓手|" + lv;
                            break;
                        case 5:
                            szname = "风水|" + lv;
                            break;
                        case 6:
                            szname = "曜魔|" + lv;
                            break;
                        case 7:
                            szname = "会长|" + lv;
                            break;
                        case 8:
                            szname = "妹|" + lv;
                            break;
                        default:
                            szname = "??|" + lv;
                            break;
                    }

                    szActionLog += szname + "、";
                    ComboBoxItem cbi = new ComboBoxItem();
                    cbi.Value = id;
                    cbi.Text = szname;
                    comboBox2.Items.Add(cbi);
                    if (id == iJobID)
                    {
                        comboBox2.SelectedIndex = iindex;
                    }
                    iindex++;
                    //                     if (id != 0 && id != 50002 && id != 50004 && id != 50005)
                    //                     {
                    //                         AreaName = nodes.SelectSingleNode("name").InnerText;
                    //                         iAreaID = id;
                    //                     }
                }
                szActionLog += "\r\n";
            }
        }

        private void GetFloorIfo()
        {
            IDictionary<string, string> parameters = new Dictionary<string, string>()
            {
                {"",""}
            };
            parameters.Clear();
            parameters.Add("area_id", Encrypt(iAreaID.ToString(), key12));
            string ulr = "http://game1-CBT.ma.sdo.com:10001/connect/app/exploration/floor?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = "game1-CBT.ma.sdo.com";
            cookies.Add(c);
            XmlDocument xml = null;

            szActionLog += "更新层数\r\n";
            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue;
                }
            }
            areaxml = xml;
            if (xml != null)
            {
                XmlNode node1 = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("exploration_floor").SelectSingleNode("floor_info_list");
                comboBox3.Items.Clear();
                foreach (XmlNode nodes in node1.ChildNodes)
                {
                    try
                    {
                        int id = int.Parse(nodes.SelectSingleNode("id").InnerText);
                        int cost = int.Parse(nodes.SelectSingleNode("cost").InnerText);
                        int progress = int.Parse(nodes.SelectSingleNode("progress").InnerText);

                        ComboBoxItem cbi = new ComboBoxItem();
                        cbi.Value = id;
                        cbi.Text = "区域" + id.ToString() + "|" + cost.ToString() + "|" + progress.ToString();
                        comboBox3.Items.Add(cbi);
                    }
                    catch (System.Exception ex)
                    {
                    	
                    }
                }
                if (comboBox3.Items.Count > 0)
                {
                    comboBox3.SelectedIndex = 0;
                }
            }
        }
        private void GetAreaIfo()
        {
            string ulr = "http://game1-CBT.ma.sdo.com:10001/connect/app/exploration/area?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = "game1-CBT.ma.sdo.com";
            cookies.Add(c);
            XmlDocument xml = null;

            szActionLog += "更新地图\r\n";
            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, null, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue;
                }
            }
            areaxml = xml;
            if (xml != null)
            {
                XmlNode node1 = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("exploration_area").SelectSingleNode("area_info_list");
                comboBox1.Items.Clear();
                foreach (XmlNode nodes in node1.ChildNodes)
                {
                    XmlNode node2 = nodes.SelectSingleNode("area_type");
                    if (node2.InnerText == "0")
                    {
                        break;
                    }
                    int id = int.Parse(nodes.SelectSingleNode("id").InnerText);

                    ComboBoxItem cbi = new ComboBoxItem();
                    cbi.Value = id;
                    cbi.Text = nodes.SelectSingleNode("name").InnerText;
                    comboBox1.Items.Add(cbi);
//                     if (id != 0 && id != 50002 && id != 50004 && id != 50005)
//                     {
//                         AreaName = nodes.SelectSingleNode("name").InnerText;
//                         iAreaID = id;
//                     }
                }
                if (comboBox1.Items.Count > 0)
                {
                    comboBox1.SelectedIndex = 0;
                }
            }
            szActionLog += "更新成功\r\n";
        }

        int ibuyCount = 0;

        private void buy(int iProduct,int icount)
        {
            IDictionary<string, string> parameters = new Dictionary<string, string>()
                {
                    {"",""}
                };
            string ulr = "http://game1-CBT.ma.sdo.com:10001/connect/app/gacha/buy?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = "game1-CBT.ma.sdo.com";
            cookies.Add(c);
            XmlDocument xml = null;
            while(true)
                try
                {
                    parameters.Clear();
                    parameters.Add("auto_build", Encrypt("0", key12));
                    parameters.Add("bulk", Encrypt("0", key12));
                    parameters.Add("product_id", Encrypt(iProduct.ToString(), key12));
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {

                }
            if (xml != null)
            {
                if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                {
                    ibuyCount = 0;
                    return;
                }
                else
                {
                    szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                    XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("your_data"); szCharName = node0.SelectSingleNode("name").InnerText + "正在挂机";
                    XmlNode nodeBC = node0.SelectSingleNode("bc");
                    BC = int.Parse(nodeBC.SelectSingleNode("current").InnerText);
                    MaxBc = int.Parse(nodeBC.SelectSingleNode("max").InnerText);
                    XmlNode nodeAP = node0.SelectSingleNode("ap");
                    AP = int.Parse(nodeAP.SelectSingleNode("current").InnerText);
                    MaxAP = int.Parse(nodeAP.SelectSingleNode("max").InnerText);
                    string strsell = "";
                    XmlNodeList nodeCardlist = null;
                    int isellnum = 0;

                    nodeCardlist = node0.SelectSingleNode("owner_card_list").SelectNodes("user_card");

                    string szLogTemp = "抽卡：ID:" + nodeCardlist[0].ChildNodes[1].InnerText + "\r\n"; ;
                    szActionLog += "[" + DateTime.Now.ToString() + "]" + szLogTemp; 
                    string szSellid = "";
                    if (ibuyCount <= icount)
                    {
                        ibuyCount++;
                        if(nodeCardlist.Count < 190)buy(iProduct, icount);
                        return;
                    }
                    foreach (XmlNode nodes in nodeCardlist)
                    {
                        int icardlv = int.Parse(nodes.SelectSingleNode("lv").InnerText);
                        int icardlvmax = int.Parse(nodes.SelectSingleNode("lv_max").InnerText);
                        int icardsale_price = int.Parse(nodes.SelectSingleNode("sale_price").InnerText);
                        int icardhp = int.Parse(nodes.SelectSingleNode("hp").InnerText);
                        int icardpower = int.Parse(nodes.SelectSingleNode("power").InnerText);
                        int iHolo = int.Parse(nodes.SelectSingleNode("holography").InnerText);
                        if (icardlv == 1)
                        {
                            if ((icardhp > 1 || icardpower > 1) && iHolo == 0 && icardlvmax < 50)
                            {
                                if (icardsale_price < iSellPrice)
                                {
                                    if (isellnum == 0)
                                    {
                                        strsell += nodes.SelectSingleNode("serial_id").InnerText;
                                    }
                                    else
                                    {
                                        strsell += "," + nodes.SelectSingleNode("serial_id").InnerText;
                                    }
                                    szSellid += "ID:" + nodes.ChildNodes[1].InnerText + " lv:" + icardlv + "/" + icardlvmax + "  atk/hp:" + icardpower + "/" + icardhp + "\r\n";
                                    isellnum++;
                                }
                            }
                        }
                        else if (icardlvmax < 50 && icardlv < 30)
                        {
                            if (isellnum == 0)
                            {
                                strsell += nodes.SelectSingleNode("serial_id").InnerText;
                            }
                            else
                            {
                                strsell += "," + nodes.SelectSingleNode("serial_id").InnerText;
                            }
                            szSellid += "ID:" + nodes.ChildNodes[1].InnerText + " lv:" + icardlv + "//" + icardlvmax + "  atk/hp:" + icardpower + "//" + icardhp + "\r\n";
                            isellnum++;
                        }
                        if (isellnum == 30)
                        {
                            szActionLog += szSellid + "\r\n";
                            if (-1 == sellcard(strsell))
                            {
                                ibuyCount = 0;
                                return;
                            }
                            isellnum = 0;
                            strsell = "";
                            szSellid = "卖：\r\n";
                        }
                    }
                    if (strsell != "")
                    {
                        szActionLog += szSellid;
                        if (-1 == sellcard(strsell))
                        {
                            ibuyCount = 0;
                            return;
                        }
                    }
                    ibuyCount = 0;
                    buy(iProduct, icount);

                }
            }
        }

        private void ChangeCard(int iCard)
        {
            if (iCardNum != iCard)
            {
                IDictionary<string, string> parameters = new Dictionary<string, string>()
                {
                    {"",""}
                };
                parameters.Clear();
                string szcardName = "";
                switch (iCard)
                {
                    case 0:
                        parameters.Add("C", Encrypt(cardFull, key12));
                        parameters.Add("lr", Encrypt(cardMr, key12));
                        szcardName = "全卡";
                        break;
                    case 1:
                        parameters.Add("C", Encrypt(card3, key12));
                        parameters.Add("lr", Encrypt(lr3, key12));
                        szcardName = "3卡";
                        break;
                    case 2:
                        parameters.Add("C", Encrypt(cardMaid, key12));
                        parameters.Add("lr", Encrypt(lrMaid, key12));
                        szcardName = "点名";
                        break;
                    case 3:
                        parameters.Add("C", Encrypt(cardwolf, key12));
                        parameters.Add("lr", Encrypt(lrwolf, key12));
                        szcardName = "狼娘";
                        break;
                    case 4:
                        parameters.Add("C", Encrypt(card6, key12));
                        parameters.Add("lr", Encrypt(lr6, key12));
                        szcardName = "6卡";
                        break;
                    case 5:
                        parameters.Add("C", Encrypt(cardSUB, key12));
                        parameters.Add("lr", Encrypt(lrSUB, key12));
                        szcardName = "SUB";
                        break;
                }
                string ulr = "http://game1-CBT.ma.sdo.com:10001/connect/app/cardselect/savedeckcard?cyt=1";
                CookieCollection cookies = new CookieCollection();
                Cookie c = new Cookie("S", szCookie);
                c.Domain = "game1-CBT.ma.sdo.com";
                cookies.Add(c);
                XmlDocument xml = null;

                while (true)
                {
                    try
                    {
                        xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                        iCardNum = iCard;
                        break;
                    }
                    catch (System.Exception ex)
                    {
                        continue;
                    }
                }
                szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                szActionLog += "[" + DateTime.Now.ToString() + "]" + "换卡：" + szcardName + "\r\n";
                actionlog.WriteInfo("换卡：" + szcardName + "\r\n");
            }
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            textBox2.Enabled = radioButton1.Checked;
            textBox3.Enabled = radioButton2.Checked;
            LoginType = radioButton1.Checked ? 0 : 1;
        }

        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            textBox2.Enabled = radioButton1.Checked;
            textBox3.Enabled = radioButton2.Checked;
            LoginType = radioButton1.Checked ? 0 : 1;
        }
        void EnableLoint(bool blogin)
        {
            if (!blogin)
            {
                textBox1.Enabled = false;
                textBox2.Enabled = false;
                textBox3.Enabled = false;
                radioButton1.Enabled = false;
                radioButton2.Enabled = false;
                button1.Enabled = false;
                button2.Enabled = true;
            }
            else
            {
                textBox1.Enabled = true;
                radioButton1.Enabled = true;
                radioButton2.Enabled = true;
                textBox2.Enabled = radioButton1.Checked;
                textBox3.Enabled = radioButton2.Checked;
                LoginType = radioButton1.Checked ? 0 : 1;
                button2.Enabled = false;
                button1.Enabled = true;
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            MainThread = new Thread(threadMain);
            MainThread.Start();
            EnableLoint(false);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            bLogin = false;
            button3.Enabled = false;
            button4.Enabled = false;
            button5.Enabled = false;
            button6.Enabled = false;
            button7.Enabled = false;
            button8.Enabled = false;
            button9.Enabled = false;
            button10.Enabled = true;
            closeThread();
            EnableLoint(true);
        }
        private void closeThread()
        {

            if (bThreadAttack)
            {
                bThreadAttack = false;
                Thread.Sleep(1000);
                AttackThread.Abort();
            }
            if (bThreadMain)
            {
                bThreadMain = false;
                Thread.Sleep(1000);
                MainThread.Abort();
            }
            if (bThreadRank)
            {
                bThreadRank = false;
                Thread.Sleep(1000);
                RankThread.Abort();
            }
            if (bThreadExplore)
            {
                bThreadExplore = false;
                Thread.Sleep(1000);
                ExploreThread.Abort();
            }
            if (bThreadRigist)
            {
                bNoLimitedBC = false;
                Thread.Sleep(1000);
                RigistThread.Abort();
            }
        }
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            closeThread();
        }
        int iTIME = 0;
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (textBoxLog.Text != szActionLog)
            {
                textBoxLog.Text = szActionLog;
                textBoxLog.SelectionStart = textBoxLog.Text.Length;
                textBoxLog.ScrollToCaret();
            }
            iTIME++;
//             if (iTIME > 100 && bThreadAttack)
//             {
//                 getGuidIFO();
//                 iTIME = 0;
//             }
            lbBCAP.Text = "BC:" + BC + "/" + MaxBc + "AP:" + AP + "/" + MaxAP;
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox1.Items != null && comboBox1.Items.Count > 0 && comboBox1.SelectedItem != null)
            {
                string text = ((ComboBoxItem)comboBox1.SelectedItem).Text;
                object vlaue = ((ComboBoxItem)comboBox1.SelectedItem).Value;
                AreaName = text;
                iAreaID = (int)vlaue;
                GetFloorIfo();
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            MapsEvent.BeginInvoke(null, EventArgs.Empty, null, null);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            Thread ranktread = new Thread(partyrank);
            ranktread.Start();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            RewardsEvent.BeginInvoke(null, EventArgs.Empty, null, null);
            button5.Enabled = false;
        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox2.Items != null && comboBox2.Items.Count > 0 && comboBox2.SelectedItem != null)
            {
                string text = ((ComboBoxItem)comboBox2.SelectedItem).Text;
                object vlaue = ((ComboBoxItem)comboBox2.SelectedItem).Value;
                changejob((int)vlaue);                
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            UpdateJob();
        }

        private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
        {

            if (comboBox3.Items != null && comboBox3.Items.Count > 0 && comboBox3.SelectedItem != null)
            {
                string text = ((ComboBoxItem)comboBox3.SelectedItem).Text;
                object vlaue = ((ComboBoxItem)comboBox3.SelectedItem).Value;
                szFloor = vlaue.ToString();
            }
        }

        private void button6_Click_1(object sender, EventArgs e)
        {
            if (!bThreadExplore)
            {
                bThreadExplore = true;
                ExploreThread = new Thread(threadExplore);
                ExploreThread.Start();
                button6.Text = "停止跑图";
            }
            else
            {
                bThreadExplore = false;
                Thread.Sleep(1000);
                ExploreThread.Abort();
                button6.Text = "挂机跑图";
            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
            ExploreEvent.BeginInvoke(null, EventArgs.Empty, null, null);
        }

        private void button8_Click(object sender, EventArgs e)
        {
            if (!bThreadAttack)
            {
                bThreadAttack = true;
                AttackThread = new Thread(threadAttack);
                AttackThread.Start();
                button8.Text = "停止攻击";
            }
            else
            {
                bThreadAttack = false;
                Thread.Sleep(1000);
                AttackThread.Abort();
                button8.Text = "连续攻击";
            }
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            bxiap = checkBox1.Checked;
        }

        private void button9_Click(object sender, EventArgs e)
        {

            if (!bNoLimitedBC)
            {
                bNoLimitedBC = true;
                RigistThread = new Thread(ThreadRigist);
                RigistThread.Start();
                button9.Text = "停止";
            }
            else
            {
                bNoLimitedBC = false;
                Thread.Sleep(1000);
                RigistThread.Abort();
                button9.Text = "刷好友";
            }
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            bAutoChange = checkBox2.Checked;
        }
        private void threadBuy71()
        {
            button10.Enabled = false;
            try
            {
                iSellPrice = int.Parse(textBox4.Text);
            }
            catch (System.Exception ex)
            {

            } 
            try
            {
                buy(31, 30);
            }
            catch (System.Exception ex)
            {

            }
            button10.Enabled = true;
        }
        private void button10_Click(object sender, EventArgs e)
        {
            Thread thread71 = new Thread(threadBuy71);
            thread71.Start();
        }

        private void label3_Click(object sender, EventArgs e)
        {

        }

        private void checkBox6_CheckedChanged(object sender, EventArgs e)
        {
            bDM = checkBox6.Checked;
        }
    }



    sealed class Log
    {
        private const string LogPath = @"action_log.txt";
        private StreamWriter log;
        public static readonly Log instance = new Log();
        private Log()
        {
            log = new StreamWriter(LogPath, true);
        }
        public void WriteInfo(string message)
        {
            WriteInfo("{0}", message);
        }
        public void WriteInfo(string format, params object[] obj)
        {
            try
            {
                log.WriteLine(string.Format("[{0}] {1}", System.DateTime.Now, string.Format(format, obj)));
                log.Flush();
            }
            catch
            {
                // Nothing to do
            }
        }
    }
    public class playerrank : IComparable<playerrank>
    {
        public string name = "";
        public int point = 0;
        public int ilv = 0;
        public int irank = 0;
        public string logintime = "";
        public override string ToString()
        {
            return string.Format("{0}，等级：{1}，贡献：{2}，排名：{3}，最后登录：{4}\r\n", this.name, this.ilv, this.point, this.irank, this.logintime);
        }

        public int CompareTo(playerrank other)
        {
            if (other == null)
                return 1;
            int value = other.point - this.point ;
            if (value == 0)
                value = this.ilv - other.ilv;
            return value;
        }
    }
    

    public class ComboBoxItem
    {
        private string _text = null;
        private object _value = null;
        public string Text { get { return this._text; } set { this._text = value; } }
        public object Value { get { return this._value; } set { this._value = value; } }
        public override string ToString()
        {
            return this._text;
        }
    }
}
